package com.stylefeng.guns.rest.modular.users.controller;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.rest.common.CommonResponse;
import com.stylefeng.guns.rest.common.base.Constans;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.common.persistence.model.IdCardBean;
import com.stylefeng.guns.rest.common.utils.TextUtil;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserIdcardRequest;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserIdcardResponseEntity;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserInfoRequest;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserRegisterParam;
import com.stylefeng.guns.rest.modular.users.service.UserIdCardService;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by ASUS-PC on 2019/9/18.
 */
@RestController
@RequestMapping("/useridcard")
public class UserIdCardController {
    private final Log logger = org.apache.commons.logging.LogFactory.getLog(this.getClass());
    private static final Charset UTF8 = Charset.forName("UTF-8");
    @Autowired
    UserIdCardService userIdCardService;


    /**
     * 获取用户是否提交认证信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/isCheck" , method = RequestMethod.POST)
    public ResponseEntity<?> getCode(@RequestBody UserInfoRequest request){
        if(request.getUserId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        IdCardBean idCardBean = userIdCardService.getUserIdcardInfo(request.getUserId());
        if(idCardBean!=null){
            return ResponseEntity.ok(CommonResponse.ok(idCardBean));
        }
        IdCardBean id = new IdCardBean();
        id.setUserId(request.getUserId());
        id.setState(-1);
        return ResponseEntity.ok(CommonResponse.ok(id));
    }

    /**
     * 用户提交认证信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/commitInfo" , method = RequestMethod.POST)
    public ResponseEntity<?> commitInfo(@RequestBody UserIdcardRequest request) throws IOException {
        if(request.getUserId()==0 || TextUtil.isEmpty(request.getIdcardNums()) ||
                TextUtil.isEmpty(request.getUserName())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        //查询是否有记录已存在
        IdCardBean idCardBean = userIdCardService.getUserIdcardInfo(request.getUserId());
        if(idCardBean!=null){
            throw new BussinessException(BizExceptionEnum.IDCARD_DERTIFY_COMMITED);
        }
        //调用阿里云接口验证信息
        String url = "https://eid.shumaidata.com/eid/check";
        String appCode = Constans.ALIYUN_IDCART_CERTIFY_APPCODE;

        Map<String, String> params = new HashMap<>();
        params.put("idcard", request.getIdcardNums());
        params.put("name", request.getUserName());

        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request rq = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(rq).execute();
        logger.info("阿里云调用身份认证返回状态码" + response.code() + ",message:" + response.message()+";当前认证用户名字："+request.getUserName());
        int code = response.code();
        if(200 == code){
            String json = getResponseString(response);
            logger.info("阿里云调用身份认证返回状态码reaponse:"+json);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String responseCode = jsonObject.getString("code");
            if("0".equals(responseCode)){
                //返回值成功,x解析res
                JSONObject object = (JSONObject) jsonObject.get("result");
                UserIdcardResponseEntity m = object.toJavaObject(UserIdcardResponseEntity.class);
                if(m!=null){
                    if("1".equals(m.getRes())){
                        //认证成功
                        int state = userIdCardService.insertUserIdcardInfo(request);
                        if(state>0){
                            return ResponseEntity.ok(CommonResponse.ok(null));
                        }
                    }else {
                        throw new BussinessException(BizExceptionEnum.IDCARD_CERTIFY_FAUL_1);
                    }
                }
            }
        }
        throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
    }

    private String getResponseString(Response response) {
        String res = "";
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        if (!bodyEncoded(response.headers())) {
            BufferedSource source = responseBody.source();
            try {
                source.request(Long.MAX_VALUE); // Buffer the entire body.
            } catch (IOException e) {
                e.printStackTrace();
            }
            Buffer buffer = source.buffer();

            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(Charset.forName("UTF-8"));
                } catch (UnsupportedCharsetException e) {
                    logger.info("TAG:"+e.getMessage());
                    e.printStackTrace();
                }
            }

            if (contentLength != 0) {
                res = buffer.clone().readString(charset);
            }
        }
        return res;
    }
    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
